<template>
  <el-container>
    <el-header style="padding: 20px 20px 0 20px;height: initial">
      <el-form label-width="0" inline>
        <el-form-item label="">
          <el-input
            v-model="searchForm.roleName"
            placeholder="角色名称(模糊匹配)"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button
            icon="el-icon-zoom-in"
            type="primary"
            plain
            @click="search"
          >查询</el-button>
          <el-button
            icon="el-icon-refresh"
            type="info"
            plain
            @click="reset"
          >清空</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            plain
            @click="add"
          >新增</el-button>

          <el-button
            icon="el-icon-close"
            type="danger"
            plain
            @click="deletes()"
          >批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <el-table
        v-loading.fullscreen.lock="loading"
        highlight-current-row
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="45"
          show-overflow-tooltip
        />
        <el-table-column
          v-for="item in tableColumn"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          show-overflow-tooltip
        >
          <div v-if="item.prop === 'imgUrl'" slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.imgUrl"
            />
          </div>
          <div v-else slot-scope="scope">{{ scope.row[item.prop] }}</div>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <div class="settings">
              <el-button
                type="warning"
                size="mini"
                plain
                @click="bindMenu(scope.row)"
              >分配菜单</el-button>
              <el-button
                type="warning"
                size="mini"
                plain
                @click="edit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="mini"
                plain
                @click="deletes([scope.row[deleteKey]])"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <el-pagination
        background
        :current-page="pageNo"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize"
        @size-change="handleChangePageSize"
        @current-change="handleChangePageNo"
      />
    </el-footer>

    <el-dialog
      :title="dialogTitle"
      width="600px"
      :visible.sync="dialogValue"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        v-if="dialogValue"
        ref="ruleForm"
        style="margin-right: 20px"
        :model="ruleForm"
        :rules="rules"
        status-icon
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="ruleForm.roleName"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          @click="save"
        >确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="角色授权"
      width="600px"
      :before-close="resetGrantForm"
      :visible.sync="dialogValue2"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        ref="ruleForm2"
        style="margin-right: 20px"
        :model="grantForm"
        status-icon
        label-width="120px"
      >
        <el-form-item label="菜单" prop="functionIdList">
          <el-tree ref="tree" :data="menus" show-checkbox node-key="id" highlight-current :props="defaultProps" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogValue2 = false">取 消</el-button>
        <el-button
          type="primary"
          @click="save2"
        >确 定</el-button>
      </span>
    </el-dialog>

  </el-container>
</template>
<style lang="less" scoped>
</style>
<script>
import { role_request as request, menu_request } from '@/api/permission'
import curd from '@/mixins/curd'
export default {
  name: 'Roles',
  mixins: [curd],
  data() {
    return {
      request: request,
      searchForm: {
        roleName: ''
      },
      tableColumn: [
        {
          prop: 'roleName',
          label: '角色名称'
        },
        {
          prop: 'createTime',
          label: '创建时间'
        }
      ],
      ruleForm: {
        id: undefined,
        roleName: ''
      },
      reseForm: {
        id: undefined,
        roleName: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      dialogValue2: false,
      menus: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentRoleId: '',
      grantForm: {
        functionIdList: []
      }
    }
  },
  created() {
    this.search()
  },
  methods: {
    formattTableData(tableData) {
      tableData.forEach(el => {
        el.createTime = new Date(el.createTime).format('yyyy-MM-dd hh:mm:ss')
      })
    },
    add() {
      this.ruleForm = { ...this.reseForm }
      this.dialogValue = true
    },
    edit(row) {
      for (const key in this.ruleForm) {
        this.ruleForm[key] = row[key]
      }
      this.ruleForm.id = row.id
      this.dialogValue = true
    },
    async save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const methodName = this.ruleForm.id ? 'edit' : 'add'
          this.request[methodName]({ ...this.ruleForm })
            .then((data) => {
              this.play.message(this, data.status, data.errorMsg)
              this.search()
              this.dialogValue = false
            })
            .catch((error) => {
              console.info(error)
            })
        }
      })
    },
    bindMenu(row) {
      this.currentRoleId = row.id
      this.dialogValue2 = true

      menu_request.tree().then(({ list }) => {
        this.menus = [{
          id: 0,
          name: '总目录',
          children: list
        }]
        this.request.getRoleBindMenu(row.id).then(res2 => {
          this.setBindMenu(res2.list)
        })
      }).catch((error) => {
        console.info(error)
      })
    },
    setBindMenu(data) {
      // data 为后台获取到的 key 数组
      // 遍历data，筛选子节点和父节点
      const checkTreeNode = []
      const parentNodes = []
      for (const item of data) {
        const node = this.$refs.tree.getNode(item)
        if (node && node.isLeaf) {
          checkTreeNode.push(item)
        } else if (node) {
          parentNodes.push(node)
        }
      }
      // 设置所有子节点选中，自动回填父节点
      this.$refs.tree.setCheckedKeys(checkTreeNode)
      // 未回填的父节点单独设置
      for (let node of parentNodes) {
        do {
          // 应当有状态的父节点在未选中时设置为半选中状态
          if (!node.checked && !node.indeterminate) {
            node.indeterminate = true
          }
          // node.indeterminate = true 仅对一个节点进行半选中状态设置，其父节点不能自动级联设置，所以这里循环设置级联父节点状态
          node = node.parent
        } while (node)
      }
    },
    save2() {
      var fatherKey = this.$refs.tree.getHalfCheckedKeys().concat(this.$refs.tree.getCheckedKeys())
      fatherKey = fatherKey.filter(f => {
        if (f !== 0) {
          return f
        }
      })
      this.request.roleBindMenu({
        'roleId': this.currentRoleId,
        'idList': fatherKey
      }).then((data) => {
        this.play.message(this, data.status, data.errorMsg)
        this.dialogValue2 = false
        this.resetGrantForm()
      }).catch((error) => {
        console.info(error)
      })
    },
    resetGrantForm() {
      this.currentRoleId = ''
      this.grantForm.functionIdList = []
      this.menus = []
      this.dialogValue2 = false
    }
  }
}
</script>
